package org.microframework.cloud.system.service.impl;

import java.util.List;
import java.util.Optional;
import org.microframework.base.core.datasource.annotation.Tx;
import org.microframework.base.core.domain.R;
import org.microframework.cloud.system.model.domain.User;
import org.microframework.cloud.system.service.ISysMenuService;
import org.microframework.cloud.system.service.ISysRoleService;
import org.microframework.cloud.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jfinal.plugin.activerecord.Db;
import lombok.extern.slf4j.Slf4j;

/**
 * 系统用户服务实现类
 * 使用JFinal ActiveRecord实现数据访问
 */
@Service
@Slf4j
public class SysUserServiceImpl implements ISysUserService {
	
    @Autowired
    private ISysRoleService roleService;
    
    @Autowired
    private ISysMenuService menuService;
    
    /**
     * 根据用户名查找用户
     */
	@Override
	public Optional<User> findByUsername(String username) {
		return findByUsernameAndNotDeleted(username);
	}

    /**
     * 查询用户的角色列表
     * 使用JFinal Db.query方法执行原生SQL
     */
	@Override
	@Tx
	public List<String> findUserRoles(String userId) {
		String sql = "SELECT r.key FROM sys_user_role ur LEFT JOIN sys_role r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.status = 0 AND r.del_flag = 0";
		return Db.query(sql, userId);
	}

    /**
     * 根据用户名查询未删除的用户
     * 使用JFinal的Model.findFirst方法
     */
    @Override
    @Tx
    public Optional<User> findByUsernameAndNotDeleted(String username) {
        org.microframework.cloud.system.model.domain.User jfinalUser = 
            org.microframework.cloud.system.model.domain.User.dao.findFirst(
                "SELECT * FROM sys_user WHERE username = ? AND del_flag = 0", username);
                
        if (jfinalUser == null) {
            return Optional.empty();
        }
        
        // 转换为系统域模型
        User user = new User();
        user.setId(jfinalUser.getId());
        user.setUsername(jfinalUser.getUsername());
        user.setPassword(jfinalUser.getPassword());
        user.setNickname(jfinalUser.getNickname());
        user.setEmail(jfinalUser.getEmail());
        user.setMobile(jfinalUser.getMobile());
        user.setStatus(jfinalUser.getStatus());
        user.setDelFlag(jfinalUser.getDelFlag());
        user.setCreateTime(jfinalUser.getCreateTime());
        user.setUpdateTime(jfinalUser.getUpdateTime());
        
        return Optional.of(user);
    }

    /**
     * 查询用户的权限列表
     * 使用JFinal的Db.query方法
     */
    @Override
    @Tx
    public List<String> findUserPermissions(String userId) {
        String sql = "SELECT DISTINCT m.perms FROM sys_menu m " +
                "INNER JOIN sys_role_menu rm ON m.id = rm.menu_id " +
                "INNER JOIN sys_user_role ur ON rm.role_id = ur.role_id " +
                "WHERE ur.user_id = ? AND m.del_flag = 0 AND m.perms IS NOT NULL AND m.perms != ''";
        return Db.query(sql, userId);
    }

    /**
     * 加载用户详情
     * 包含事务控制
     */
	@Override
	@Tx
	public R<?> loadUserByUsername(String username) {
        // 从数据库查询用户
        User user = findByUsernameAndNotDeleted(username)
                .orElse(null);
                
        if (user == null) {
            log.warn("用户不存在: {}", username);
            return R.fail("用户不存在");
        }
                
        // 检查用户状态
        if (user.getStatus() != 0) {
            log.warn("用户[{}]已停用", username);
            return R.fail("用户已停用");
        }
        
        // 查询用户角色和权限
        List<String> roles = roleService.findRolesByUserId(user.getId());
        List<String> permissions = menuService.findPermissionsByUserId(user.getId());
        
        // 构建自定义用户对象
        user.setRoles(roles);
        user.setPermissions(permissions);
            
        log.info("用户[{}]登录成功", username);
		return R.ok(user);
	}
	
	/**
     * 创建用户
     * 使用JFinal事务注解和ActiveRecord模型
     */
    @Tx
    public boolean createUser(User user) {
        try {
            org.microframework.cloud.system.model.domain.User jfinalUser = 
                new org.microframework.cloud.system.model.domain.User();
                
            // 设置用户信息
            jfinalUser.setId(user.getId());
            jfinalUser.setUsername(user.getUsername());
            jfinalUser.setPassword(user.getPassword());
            jfinalUser.setNickname(user.getNickname());
            jfinalUser.setEmail(user.getEmail());
            jfinalUser.setMobile(user.getMobile());
            jfinalUser.setStatus(user.getStatus());
            jfinalUser.setDelFlag(0); // 默认未删除
            jfinalUser.setCreateTime(user.getCreateTime());
            jfinalUser.setCreateBy(user.getCreateBy());
            
            // 保存用户
            return jfinalUser.save();
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return false;
        }
    }
    
    /**
     * 更新用户
     * 使用JFinal事务注解和ActiveRecord模型
     */
    @Tx
    public boolean updateUser(User user) {
        try {
            // 先查询用户
            org.microframework.cloud.system.model.domain.User jfinalUser = 
                org.microframework.cloud.system.model.domain.User.dao.findById(user.getId());
                
            if (jfinalUser == null) {
                return false;
            }
            
            // 更新用户信息
            jfinalUser.setNickname(user.getNickname());
            jfinalUser.setEmail(user.getEmail());
            jfinalUser.setMobile(user.getMobile());
            jfinalUser.setStatus(user.getStatus());
            jfinalUser.setUpdateTime(user.getUpdateTime());
            jfinalUser.setUpdateBy(user.getUpdateBy());
            
            // 更新用户
            return jfinalUser.update();
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return false;
        }
    }
}
